package com.asiainfo.ncrm;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.asiainfo.ncrm.base.BaseHttp;
import com.asiainfo.ncrm.base.UploadUtil;
import com.asiainfo.ncrm.base.UploadUtil.OnUploadProcessListener;
import com.asiainfo.ncrm.base.VolleyController;
import com.asiainfo.ncrm.common.Constant;
import com.asiainfo.ncrm.popup.BottomMenuPopupWindow;
import com.asiainfo.ncrm.util.AntConstant;
import com.asiainfo.ncrm.util.DESEngine;
import com.asiainfo.ncrm.util.X;
//import com.changda.camera.util.PicOperation;
//import com.changda.camera.util.callback.UploadCallback;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class getPhotoActivity extends Activity implements OnUploadProcessListener{

	private ImageView front_photo;//正面图
	private ImageView back_photo;//背面图
	private ImageView order_photo;
	private ImageView back_photo_show;
	private ImageView top_iv_left;
	private ImageView front_photo_show;


	private Button savephoto;

	protected BaseHttp bh ;

	public static final int RESULT_FRONT= 1;

	public static final int RESULT_BACK=2;

	public static final int RESULT_ORDER=3;

	private Bitmap front;

	private Bitmap back;

	private File frontFile;

	private File backFile;

	private File orderFile;

	public Context mcontext ;

	private static final String TAG = "uploadFile";
	private static final int TIME_OUT = 10*10000000; //超时时间
	private static final String CHARSET = "utf-8"; //设置编码
	public static final String SUCCESS="1"; public static final String FAILURE="0";

	private String tempName;

	String PREFIX = "--" , LINE_END = "\r\n";

	private BottomMenuPopupWindow popupWindow;

	private String action="syncdata";

	private String servicetype="1";

	private String custorder="20160702900131";

	private String custname="";

	private String createdate="";

	private String bookingman="20066";

	private String businessarea="";

	private String businesspoint="";


	private Map<Object, Object> map;

	/**
	 * 去上传文件
	 */
	protected static final int TO_UPLOAD_FILE = 1;
	/**
	 * 上传文件响应
	 */
	protected static final int UPLOAD_FILE_DONE = 2;  //
	/**
	 * 选择文件
	 */
	public static final int TO_SELECT_PHOTO = 3;
	/**
	 * 上传初始化
	 */
	private static final int UPLOAD_INIT_PROCESS = 4;
	/**
	 * 上传中
	 */
	private static final int UPLOAD_IN_PROCESS = 5;

	private ProgressBar progressBar;

	private TextView uploadImageResult;

	private ProgressDialog progressDialog;

	private Context mContext;

	String olNbr = "";
	String staffId= "";
	String username= "";

	List<File> uploadRow= new ArrayList<File>();//创建上传队列


	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case TO_UPLOAD_FILE:
					toUploadFile();
					break;

				case UPLOAD_INIT_PROCESS:
					progressBar.setMax(msg.arg1);
					break;
				case UPLOAD_IN_PROCESS:
					progressBar.setProgress(msg.arg1);
					break;
				case UPLOAD_FILE_DONE:
					String result = "响应码："+msg.arg1+"\n响应信息："+msg.obj+"\n耗时："+UploadUtil.getRequestTime()+"秒";
					uploadImageResult.setText(result);
					break;
				default:
					break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_getphoto);

		mContext= this;

		Intent intent = getIntent();

		String param = intent.getStringExtra("param");
		JSONObject parmJson = null;
		try{
			parmJson = new JSONObject(param);
			olNbr = parmJson.getString("olNbr");
			staffId = parmJson.getString("staffId");
			username = parmJson.getString("userName");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		SimpleDateFormat dateFormater=new SimpleDateFormat("yyyyMMddhhmmss");
		Date date=new Date();
		createdate=(dateFormater.format(date));

		uploadImageResult = (TextView) findViewById(R.id.uploadImageResult);
		progressDialog = new ProgressDialog(this);
		progressBar = (ProgressBar) findViewById(R.id.progressBar1);

		init();

		//getPhotoByNbr();
	}

	public void init(){ //初始化按钮
		mcontext= this;
		front_photo = (ImageView) findViewById(R.id.front_photo);
		back_photo = (ImageView) findViewById(R.id.back_photo);
		order_photo = (ImageView) findViewById(R.id.order_photo);
		back_photo_show=(ImageView) findViewById(R.id.back_photo_show);
		front_photo_show = (ImageView) findViewById(R.id.front_photo_show);
		savephoto  = (Button) findViewById(R.id.savephoto);
		top_iv_left = (ImageView)findViewById(R.id.top_iv_left);
		bh= new BaseHttp(this);

		front_photo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				//调用摄像机方法
//				letCamera(RESULT_FRONT);
				popupWindow = new BottomMenuPopupWindow(mcontext, front_photo,RESULT_FRONT);
				popupWindow.show();
			}
		});
		front_photo_show.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				//调用摄像机方法
//						letCamera(RESULT_FRONT);
			}
		});


		back_photo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
//				letCamera(RESULT_BACK);
				popupWindow = new BottomMenuPopupWindow(mcontext, back_photo, RESULT_BACK);
				popupWindow.show();
			}
		});

		back_photo_show.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
//						letCamera(RESULT_BACK);
			}
		});

		order_photo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO 自动生成的方法存根
				//调用摄像机方法
//				letCamera(RESULT_FRONT);
				popupWindow = new BottomMenuPopupWindow(mcontext, order_photo,RESULT_ORDER);
				popupWindow.show();
			}
		});

		top_iv_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				pageSure(view,2);
			}
		});

		savephoto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				//if(frontFile != null && backFile != null){
				if (frontFile != null  ||orderFile != null || backFile != null) {
					//封装参数
//					byte[] frontbyte = front.get
//					String frontbase = bitToBase64(front);
//					String backbase = bitToBase64(back);
//					
//					String imagepost = Constant.IMAGE_UPLOAD_URL;

//					handler.sendEmptyMessage(TO_UPLOAD_FILE);
//					String uploadresult= uploadFile(Constant.IMAGE_UPLOAD_URL, frontFile);
//					if(uploadresult.equals("1")){
//						Toast.makeText(mcontext, "第一张图片上传完毕", Toast.LENGTH_SHORT).show();
////						uploadresult = uploadFile(Constant.IMAGE_UPLOAD_URL, backFile);
//						
//					}
//					try {
//						PicOperation picOperation = new PicOperation();
//						HashMap map = new HashMap();
//						map.put("custorder", olNbr);
//						map.put("custname", "");
//						map.put("createdate", createdate);
//						map.put("bookingman", username);
//						map.put("Businesstype", "拍照业务");
//						map.put("businessnum", staffId);
//
//						X.d(mContext, "第一次点击");
//						X.d(mContext, frontFile.getAbsolutePath());
//
//						uploadRow.clear();
//
//						uploadRow.add(frontFile);
//						uploadRow.add(backFile);
//						uploadRow.add(orderFile);
//
//						for (File io : uploadRow) {
//							picOperation.upload(io, map, new UploadCallback() {
//								/*	File path = new File(Environment.getExternalStorageDirectory().toString() + "/image/1482987735367.jpg");
//                                    if(frontFile.exists())
//                                    {
//                                        System.out.println("cun zai de!!!!!!!!");
//                                    }
//                                    picOperation.upload(frontFile, map, new UploadCallback() {
//                                */
//								@Override
//								public void result(int resultcode, String result) {
//									System.out.println("result :" + result);
//									//Toast.makeText(mcontext, result, Toast.LENGTH_SHORT).show();
//
//								}
//							});
//						}
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
				} else {
					Toast.makeText(mcontext, "照片没有全拍摄完毕", Toast.LENGTH_SHORT).show();
					return;
				}
				pageSure(v,RESULT_OK);
			}

		});
	}


	public void pageSure(View v,int res){
		Intent intent = getIntent();
		Bundle bundle = new Bundle();

		intent.putExtras(bundle);
		this.setResult(res, intent);//返回页面1
		this.finish();

	}

	public void getPhotoByNbr(){
		String result = "";

		Object localObject = "Wzhbgapp2015";
		String str11 = "20161110910546," + System.currentTimeMillis();
		String str12 = null;
		DESEngine localDESEngine = new DESEngine();
		try
		{
			str12 = localDESEngine.encrypt((String)localObject, str11);
		}
		catch (Exception localException)
		{
		}

		String url = "http://222.83.4.36:8080/public/query?custorder=20161110910546&servicetype=1&token=";

//		String time= String.valueOf( (new Date()).getTime());
//
//		String token =encrypt("20161110910546,"+time,Constant.WUZHIHUA);

		StringRequest instance = new StringRequest(url+str12, new  Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO 自动生成的方法存根
				try{
					X.d(mContext,response);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO 自动生成的方法存根
//				Toast.makeText(context, "登录失败，请重试", Toast.LENGTH_LONG).show();
//				XUtils.showText("服务端访问出错，" + error.getMessage());
				try {
				} catch (Exception e) {
				}

			}
		}) ;
		instance.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
		// RequestQueue queue = Volley.newRequestQueue(context);
		VolleyController.getInstance(mContext).addToRequestQueue(instance);


	}


	/**
	 * 加密
	 *
	 * @param content 需要加密的内容
	 * @param password  加密密码
	 * @return
	 */
	public static String encrypt(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result.toString(); // 加密
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public String uploadFile(String RequestURL,File file){
		String CONTENT_TYPE = "multipart/form-data"; //内容类型   
		try {
			String BOUNDARY = UUID.randomUUID().toString();
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); //允许输入流
			conn.setDoOutput(true); //允许输出流
			conn.setUseCaches(false); //不允许使用缓存
			conn.setRequestMethod("POST"); //请求方式
			conn.setRequestProperty("Charset", CHARSET);
			//设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
			if(file!=null) {
				/** * 当文件不为空，把文件包装并且上传 */
				OutputStream outputSteam=conn.getOutputStream();
				DataOutputStream dos = new DataOutputStream(outputSteam);
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意：
				 * name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */
				sb.append("Content-Disposition: form-data; name=\"img\"; filename=\""+file.getName()+"\""+LINE_END);
				sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());
				InputStream is = new FileInputStream(file);
				byte[] bytes = new byte[1024];
				int len = 0;
				while((len=is.read(bytes))!=-1)
				{
					dos.write(bytes, 0, len);
				}
				is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功
				 * 当响应成功，获取响应的流
				 */
				int res = conn.getResponseCode();
				Log.e(TAG, "response code:"+res);
				if(res==200)
				{
					return SUCCESS;
				}
			}
		} catch (MalformedURLException e)
		{ e.printStackTrace(); }
		catch (IOException e)
		{ e.printStackTrace(); }
		return FAILURE;
	}

	public void letCamera(int type){
		//调用拍照
		Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String strImgPath = Environment.getExternalStorageDirectory()
				.toString() + "/ncrm/";// 存放照片的文件夹
		String fileName =  (new Date()).getTime()+".jpg";// 照片命名
		tempName= fileName;
		File out = new File(strImgPath);
		if (!out.exists()) {
			out.mkdirs();
		}
		out = new File(strImgPath, fileName);
		strImgPath = strImgPath + fileName;// 该照片的绝对路径
		Uri uri = Uri.fromFile(out);
		imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
		imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
		startActivityForResult(imageCaptureIntent, type);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		map=null;
		if (resultCode == RESULT_OK) {
			map = popupWindow.doPhoto(requestCode, resultCode,data);
		}
		X.d(mcontext, resultCode);
		if(map !=null){
			Bitmap photo=null;
			if(requestCode==0){
				Bundle extras = data.getExtras();
				photo = extras.getParcelable("data");
			}

			if(map.containsKey(RESULT_FRONT)){
				front= photo;
				String frontpath = map.get(RESULT_FRONT).toString();
				frontFile = new File(AntConstant.IMAGE_DIR+frontpath);

				X.d(mContext,"图片路径:"+frontFile.getAbsolutePath());
//        		Toast.makeText(mcontext, frontpath, Toast.LENGTH_SHORT).show();
			}else if(map.containsKey(RESULT_BACK)){
				back= photo;
				String backpaht =  map.get(RESULT_BACK).toString();
				backFile = new File(AntConstant.IMAGE_DIR+backpaht);
				X.d(mContext,"图片路径:"+backFile.getAbsolutePath());
//        		Toast.makeText(mcontext, backpaht, Toast.LENGTH_SHORT).show();
			}
			else if(map.containsKey(RESULT_ORDER))
			{
				back= photo;
				String backpaht =  map.get(RESULT_ORDER).toString();
				orderFile = new File(AntConstant.IMAGE_DIR+backpaht);
				X.d(mContext,"图片路径:"+orderFile.getAbsolutePath());
			}
		}
	}

	public Bitmap exifImage(File file){
		Bitmap bitmap =null;
//	           ExifInterface exifInterface = new ExifInterface(file.getPath());   
//	           int result = exifInterface.getAttributeInt(   
//	                   ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);   
		int rotate = 0;
//	           switch(result) {   
//	           case ExifInterface.ORIENTATION_ROTATE_90:   
//	               rotate = 90;   
//	               break;   
//	           case ExifInterface.ORIENTATION_ROTATE_180:   
//	               rotate = 180;   
//	               break;   
//	           case ExifInterface.ORIENTATION_ROTATE_270:   
//	               rotate = 270;   
//	               break;   
//	           default:   
//	               break;   
//	           }   
//	           BitmapFactory.Options options = new BitmapFactory.Options();  
//	           options.inPreferredConfig = Bitmap.Config.RGB_565;  
//	           // 初めのデコードはサイズ取得のみ  
//	           options.inJustDecodeBounds = true;  
//	           BitmapFactory.decodeFile(file.getPath(), options);  
//	           
//	           if(options.outWidth < options.outHeight){
//	        	   rotate=90;
//	           }
//	              
////	           scallType = genScallType(context, options);  
//	             
//	           options.inJustDecodeBounds = false;  
		bitmap=  BitmapFactory.decodeFile(file.getPath());
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();

		int newWidth = 800;
		int newHeight = 450;

		//计算缩放率，新尺寸除原始尺寸
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		if(width <= height){
			rotate=90;
		}

		Matrix matrix = new Matrix();

		matrix.postScale(scaleWidth, scaleHeight);
		matrix.setRotate(rotate);
		Bitmap rotateBitmap = Bitmap.createBitmap(
				bitmap, 0, 0, width, height, matrix, true);
		if(rotateBitmap != null) {
			bitmap.recycle();
			bitmap = rotateBitmap;
		}
		return bitmap;
	}

	public String bitToBase64(Bitmap bit){
		String result ="";
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			bit.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();

			out.close();

			byte[] frontbyte = out.toByteArray();
			// 将普通字节数组转换为base64数组
			result = Base64.encodeToString(frontbyte, Base64.DEFAULT);

		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return result;
	}


	private void toUploadFile()
	{
		uploadImageResult.setText("正在上传中...");
		progressDialog.setMessage("正在上传文件...");
		progressDialog.show();
		String fileKey = "content";
		UploadUtil uploadUtil = UploadUtil.getInstance();;
		uploadUtil.setOnUploadProcessListener(this);  //设置监听器监听上传状态

		Map<String, Object> params = new HashMap<String, Object>();
		params.put("action", action);
		params.put("servicetype", servicetype);
		params.put("custorder", custorder);
		params.put("custname", custname);
		params.put("createdate", createdate);
		params.put("bookingman", bookingman);
		params.put("businessarea", businessarea);
		params.put("businesspoint", businesspoint);
		String frontString = bitToBase64(front);
		String backString = bitToBase64(back);
//	        String s=custorder+" 20066 "+System.currentTimeMillis();
//	        DESEngine des = new DESEngine();
//	        String cw= "";
//	        try {
//				 cw = des.encrypt("Wzhbgapp2015", s);
//				params.put("cw", cw);
//			} catch (Exception e) {
//				// TODO 自动生成的 catch 块
//				e.printStackTrace();
//			}
		params.put("cw", "897fbc7ed1682af897717bc0b3a26b834a84e9730b2a2f686124ccfbe3083c5774a56ecece6a840b");
		X.d("cw", "897fbc7ed1682af897717bc0b3a26b834a84e9730b2a2f686124ccfbe3083c5774a56ecece6a840b");
		X.d("photo", frontString);
		X.d("photo", backString);
		String photoList = "['data:image/jpeg;base64,"+frontString+"']";
//	        String[] photoList = new String[]{frontString,backString};
		params.put("data", photoList);


//	        params.put("cw", cw);
//	        params.put("", value)
//	        params.put("createdate", createdate);
		uploadUtil.uploadFile( frontFile,fileKey, Constant.IMAGE_UPLOAD_URL,params);
	}


	@Override
	public void onUploadProcess(int uploadSize) {
		Message msg = Message.obtain();
		msg.what = UPLOAD_IN_PROCESS;
		msg.arg1 = uploadSize;
		handler.sendMessage(msg );
	}

	@Override
	public void initUpload(int fileSize) {
		Message msg = Message.obtain();
		msg.what = UPLOAD_INIT_PROCESS;
		msg.arg1 = fileSize;
		handler.sendMessage(msg );
	}

	@Override
	public void onUploadDone(int responseCode, String message) {
		// TODO 自动生成的方法存根
		progressDialog.dismiss();
		Message msg = Message.obtain();
		msg.what = UPLOAD_FILE_DONE;
		msg.arg1 = responseCode;
		msg.obj = message;
		handler.sendMessage(msg);

	}


	//第三方图片上传
}
